package com.example.gybicycle.common.security;


import com.example.gybicycle.common.util.LoginUtil;
import com.example.gybicycle.entity.LoginInfo;
import com.google.common.collect.Lists;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author jqllxew
 * 2020/10/22.
 */
public class AuthRealm extends AuthorizingRealm {
    public AuthRealm(CredentialsMatcher credentialsMatcher){
        this.setCredentialsMatcher(credentialsMatcher);
    }
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Token;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String token = (String) principalCollection.getPrimaryPrincipal();
        LoginInfo user = LoginUtil.getLoginInfo(token);
        SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
        sa.addStringPermissions(user.getPermissions()!=null?user.getPermissions(): Lists.newArrayList(""));
        return sa;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        Token t = (Token) token;
        return new SimpleAuthenticationInfo(t.getToken(),"",getName());
    }
}
